using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;

namespace ReactiveLang
{
    class Sync
    {
        SynchronizationContext _ctx = SynchronizationContext.Current;
        Thread _origThread = Thread.CurrentThread;

        public Sync()
        {
            if (_ctx == null)
                throw new InvalidOperationException("SynchronizationContext.Current is null");
        }

        public void SameThread(Action task)
        {
            Contract.Requires(task != null);
            if (_origThread != Thread.CurrentThread)
                Post(task);
            else
                task();
        }
        public void Post(Action task)
        {
            Contract.Requires(task != null);
            _ctx.Post(delegate { task(); }, null);
        }
    }
}